/*
 *
 *  Copyright (C) 2008-2010 GSyC/LibreSoft, Universidad Rey Juan Carlos
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see http://www.gnu.org/licenses/. 
 *
 *  Author : Roberto Calvo Palomino <rocapal@gsyc.es>
 *
 */

package com.LibreGeoSocial.App;

import java.io.BufferedOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;

import com.LibreGeoSocial.Api.Audio;
import com.LibreGeoSocial.Api.LibreGeoSocial;
import com.LibreGeoSocial.App.Multimedia.AudioManager;
import com.LibreGeoSocial.App.Routes.LocationService;
import com.LibreGeoSocial.App.Utils.LocationUtils;


public class AudioCard extends GenericCard {

	
	private ImageView imageAudio;
	private TextView lbTitle, lbBody, lbDate, lbDist, lbUploader;
	private ScrollView lbscroll;
	private Audio mAudio;
	private AudioManager Am;
	private InputStream audio;
	private String name;
	private String tmp_path;
	
	private static final int MENU_SHARE = Menu.FIRST + 20;
	private static final int MENU_OPEN = Menu.FIRST + 10;

	private static com.LibreGeoSocial.App.Multimedia.AudioManager aManager;
	
    public void onCreate(Bundle icicle) {
    	
         super.onCreate(icicle);
         
         setContentView(R.layout.generic_card);
         
         OnClickListener showAudio = new OnClickListener() {
       		public void onClick(View view) {
       			loadAudio(true);
       		}
       	 };
       	 
         mAudio = (Audio) mNode;
         
         tmp_path = getResources().getString(R.string.urlServer);
 		 
 		 name = mAudio.getName().replace(" ", "_");
		 audio = mAudio.getAudio();

         
         imageAudio = (ImageView)this.findViewById(R.id.img);
         imageAudio.setImageResource(R.drawable.audio_100);
         imageAudio.setClickable(true);
         imageAudio.setOnClickListener(showAudio);
  		
 		 Am = new AudioManager(this);
 		 Am.saveAudio(audio, name);

         lbTitle = (TextView) this.findViewById(R.id.lbTitle);
         lbBody = (TextView) this.findViewById(R.id.lbBody);   
         lbDate = (TextView) this.findViewById(R.id.lbDate);
         lbDist = (TextView) this.findViewById(R.id.lbDist);
         lbUploader = (TextView) this.findViewById(R.id.lbUploader);

         
         lbTitle.setText (mAudio.getName());
         lbBody.setText  (mAudio.getDescription());
         lbDate.setText  ("Date: " + mAudio.getSince().split(" ")[0]); 
         
         //Calculate distance
         float dist = LocationUtils.calculateDistance (LocationService.getCurrentLocation(),
        		 	mAudio.getLocation());
         
         lbDist.setText ("Distance: " + LocationUtils.displayDistance(dist, LocationUtils.AUTO));
           
         setIconId(R.drawable.audio_48);
         showMap(mAudio.getLongitude(), mAudio.getLatitude());
         
    }

	private void loadAudio(Boolean onCard) {

		if (onCard) {
			aManager = new com.LibreGeoSocial.App.Multimedia.AudioManager(this);
			if(aManager.isPlaying())
				return;
			// Downloading
			InputStream is = LibreGeoSocial.getInstance().getAudio(mAudio.getUrl());

			aManager.saveAudio (is,name);

			// Playing audio    		
			aManager.startPlayer();
	
		}
		else {
				
		//create the dir if not exists
		File dirhandler = new File (tmp_path);
        if(! dirhandler.exists())
          dirhandler.mkdirs();
        
        try {
        	DataOutputStream out = new DataOutputStream(
				new BufferedOutputStream(
						new FileOutputStream( tmp_path + name.replace(" ", "_") + ".3gpp")));
        
        	int c;
        	while((c = audio.read()) != -1) {
        		out.writeByte(c);
        	}
        	out.flush();
        	audio.close();
        	out.close();
        } catch (FileNotFoundException e) {
			Log.e("AudioManager: ", e.getMessage());
		}catch(IOException e) {
			Log.e("AudioManager: ", e.getMessage());
		}
		
		Intent i = new Intent(android.content.Intent.ACTION_VIEW);
        i.setDataAndType(Uri.fromFile(new File(Am.getPath())), "audio/3gpp");
        startActivity(i);
		
		}
	}
	
	@Override
    public boolean onCreateOptionsMenu(Menu menu) {
    	
        super.onCreateOptionsMenu(menu);
                
        menu.add(0, MENU_SHARE, 0, "Share")
        .setAlphabeticShortcut('B')
		.setIcon(R.drawable.up);

        menu.add(0, MENU_OPEN, 0, "Open Media")
        .setAlphabeticShortcut('A')
        .setIcon(R.drawable.media)
		.setIcon(R.drawable.audio_48);

		        
        return true;
	}
	
    @Override
    public boolean onOptionsItemSelected (MenuItem item) {

    	switch (item.getItemId()) {
    
    		case MENU_SHARE:  			

    			aManager = new com.LibreGeoSocial.App.Multimedia.AudioManager(this);
    			InputStream is = LibreGeoSocial.getInstance().getAudio(mAudio.getUrl());

    			aManager.saveAudio (is,name);

    			
                Intent i = new Intent(Intent.ACTION_SEND);
                i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                i.putExtra(Intent.EXTRA_TEXT, mAudio.getDescription());
                i.setType("image/jpeg");
                i.putExtra(Intent.EXTRA_SUBJECT, "[LGS-Audio] " + mAudio.getName());
                i.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File(Am.getPath())));
                startActivity(i);
    		
    		case MENU_OPEN:
    			
    			loadAudio(false);

    	}

    	return super.onOptionsItemSelected(item);
    }

	@Override
	protected boolean isRouteDisplayed() {
		// TODO Auto-generated method stub
		return false;
	}
	

}


